package com.zzw.controller;

import com.google.gson.Gson;
import com.zzw.bean.Msg;
import com.zzw.bean.TabBean;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import sun.misc.BASE64Encoder;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.lang.reflect.InvocationTargetException;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

/**
 * @author 赵志伟
 * @version 1.0
 */
@SuppressWarnings({"all"})
@Controller
public class IndexController {

    @RequestMapping({"/login", "/"})
    public String login() {
        return "login";
    }

    @RequestMapping("/animate")
    public String animate() {
        return "animate";
    }

    @RequestMapping("/unauthorized")
    public String unauthorized() {
        return "unauthorized";
    }

    @RequestMapping(value = "demo/treegrid")
    public String treeGird() {
        return "treegrid/list";
    }

    @RequestMapping(value = "demo/combotree")
    public String combotree() {
        return "combotree/list";
    }

    @RequestMapping(value = "demo/wordDocument")
    public String wordDocument() {
        return "wordDocument/list";
    }

    @RequestMapping(value = "demo/tabs")
    public String tabs() {
        return "tabs/list";
    }

    @RequestMapping(value = "demo/tab1")
    public String tab1() {
        return "iframe/tab1";
    }

    @RequestMapping(value = "demo/tab2")
    public String tab2() {
        return "iframe/tab2";
    }

    @RequestMapping(value = "demo/iframe")
    public String iframe() {
        return "iframe/list";
    }

    @RequestMapping(value = "demo/child")
    public String child() {
        return "iframe/child";
    }

    @RequestMapping(value = "demo/textbox")
    public String textbox() {
        return "textbox/list";
    }

    @RequestMapping(value = "demo/es6")
    public String es6() {
        return "es6/list";
    }

    @RequestMapping(value = "blob/list")
    public String blob() {
        return "blob/list";
    }


    @RequestMapping("tabSave")
    @ResponseBody
    public Msg tabSave(@RequestParam("productImage") MultipartFile file, TabBean tabBean) {

        Gson gson = new Gson();
        String json = gson.toJson(tabBean);

        FileOutputStream fileOutputStream = null;
        try {
           fileOutputStream = new FileOutputStream("E:\\idea_project\\zzw_ssm\\furn-ssm-easyui\\src\\main\\webapp\\WEB-INF\\static\\js\\owner\\tab.json", true);
            fileOutputStream.write(json.getBytes());
            fileOutputStream.close();
            return Msg.success();
        } catch (Exception e) {
            return Msg.fail();
        } finally {
            try {
                fileOutputStream.close();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
    }

    @RequestMapping("wordDocument") // 映射请求路径为 "wordDocument"
    public void readWord(@RequestParam("file") MultipartFile file) throws IOException {
        // 从上传的文件中获取输入流
        InputStream inputStream = file.getInputStream();

        // 使用输入流创建 XSSFWorkbook 对象，表示 Excel 工作簿
        XSSFWorkbook workbook = new XSSFWorkbook(inputStream);
        // 获取工作簿中的总表数量
        int numberOfSheets = workbook.getNumberOfSheets();

        // 获取第一个工作表
        XSSFSheet sheet = workbook.getSheetAt(0);
        // 获取表的起始行号和结束行号
        int firstRowNum = sheet.getFirstRowNum();
        int lastRowNum = sheet.getLastRowNum();

        // 创建一个字符串列表，用于存储格式化后的日期
        List<String> list = new ArrayList<>();
        File f = null;

        // 遍历表中每一行（从第一行开始，忽略标题行）
        for (int i = firstRowNum + 1; i < lastRowNum; i++) {
            // 获取当前行第一个单元格的日期值
            Date date = sheet.getRow(i).getCell(0).getDateCellValue();
            // 将日期格式化为 "yyyy-MM-dd" 的字符串
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            String format = sdf.format(date);

            // 在指定路径下创建一个以日期为名称的文件夹
            File file1 = new File("E:\\Programs\\desktop\\我的工作", format);
            if (!file1.exists()) { // 如果文件夹不存在，则创建
                file1.mkdirs();
            }
            // 将格式化后的日期添加到列表中
            list.add(format);
        }
        // 打印生成的日期列表
        System.out.println(Arrays.asList(list));
    }


    @RequestMapping("createExcel")
    public void createExcel(HttpServletRequest request, HttpServletResponse response) throws IOException, NoSuchMethodException, InvocationTargetException, IllegalAccessException {
        //1.创建工作簿
        XSSFWorkbook workbook = new XSSFWorkbook();
        //2.
        XSSFSheet sheet = workbook.createSheet("第一个sheet页");
        //3.创建行
        //表头
        //数据
        XSSFRow firstRow = sheet.createRow(0);
        //4.表头
        String[] headers = {"编号", "年龄", "班级"};
        for (int i = 0; i < headers.length; i++) {
            XSSFCell cell = firstRow.createCell(i);
            cell.setCellValue(headers[i]);
        }
        //5.内容
        //Gson gson = new Gson();
        //TypeToken<List<Book>> typeToken = new TypeToken<List<Book>>() {};
        //List<Book> bookList = gson.fromJson(readText(), typeToken.getType());
        //for (int i = 0; i < bookList.size(); i++) {
        //    XSSFRow row = sheet.createRow(i + 1);//创建该行
        //
        //    Book book = bookList.get(i);
        //    Class<? extends Book> clazz = book.getClass();
        //    Field[] declaredFields = clazz.getDeclaredFields();
        //    for (int j = 0; j < declaredFields.length; j++) {
        //        Field field = declaredFields[j];
        //        XSSFCell cell = row.createCell(j);
        //
        //        String fieldName = field.getName();
        //        String methodName = "get" + fieldName.substring(0, 1).toUpperCase() + fieldName.substring(1);
        //        Method getMethod = clazz.getDeclaredMethod(methodName);
        //        Class<?> returnType = getMethod.getReturnType();
        //        getMethod.setAccessible(true);
        //        Object invoke = getMethod.invoke(book);
        //        System.out.println(invoke);
        //        cell.setCellValue(invoke.toString());
        //    }
        //}
        //5.下载
        String fileName = "我的excel.xlsx";
        if (request.getHeader("User-Agent").contains("Firefox")) {
            // 火狐 Base64编码
            response.setHeader("Content-Disposition", "attachment; filename==?UTF-8?B?" +
                    new BASE64Encoder().encode(fileName.getBytes("UTF-8")) + "?=");
        } else {
            // 其他(主流ie/chrome)使用URL编码操作
            response.setHeader("Content-Disposition", "attachment; filename=" +
                    URLEncoder.encode(fileName, "UTF-8"));
        }

        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        ServletOutputStream outputStream = response.getOutputStream();
        workbook.write(outputStream);
    }

    // 在应用启动类添加验证
    public static void main(String[] args) {
        try {
            Class.forName("com.google.gson.Gson");
            System.out.println("Gson 类加载成功");
        } catch (ClassNotFoundException e) {
            System.err.println("Gson 类加载失败");
        }
        // ...其他启动代码
    }
    public String readText() throws IOException {
        String file = "E:\\idea_project\\zzw_ssm\\furn-ssm-easyui\\src\\main\\webapp\\WEB-INF\\static\\js\\owner\\mytest.json";

        //一次读取8个字节
        BufferedReader bufferedReader = null;
        bufferedReader = new BufferedReader(new FileReader(file));
        //按行读取
        String line;

        //存
        StringBuilder stringBuilder = new StringBuilder();

        while ((line = bufferedReader.readLine()) != null) {
            stringBuilder.append(line);
        }

        bufferedReader.close();

        return stringBuilder.toString();
    }
}
